# save this as app.py
import io 
import base64
import time

from flask import render_template
from PIL import Image
from flask_socketio import SocketIO

import config
from models.data_model import Person

global acquisition_ongoing
acquisition_ongoing = False
app = config.connex_app
app.add_api(config.basedir / "swagger.yml")
socketio = SocketIO(config.app, max_http_buffer_size = 10000000)

@app.route("/")
def hello():
    people = Person.query.all()
    return render_template("home.html", people = people)

@socketio.on("acquisition_start")
def reconstruct_image_realtime(message):
    print(f"received message: {message}")
    number = 1
    global acquisition_ongoing
    acquisition_ongoing = True

    while acquisition_ongoing:

        number = number + 1
        if number%6 == 0:
            img = Image.open("./matlab_scripts/const_file/HHb_result.bmp")
        elif number%6 == 1:
            img = Image.open("./matlab_scripts/const_file/Hb_result.bmp")
        elif number%6 == 2:
            img = Image.open("./matlab_scripts/const_file/BOS_result.bmp")
        elif number%6 == 3:
            img = Image.open("./matlab_scripts/const_file/collagen_result.bmp")
        elif number%6 == 4:
            img = Image.open("./matlab_scripts/const_file/lipid_result.bmp")
        elif number%6 == 5:
            img = Image.open("./matlab_scripts/const_file/mineral_result.bmp")

        image_object = io.BytesIO()
        img.save(image_object, "bmp")
        bmp_data_bytes = image_object.getvalue()
        socketio.emit("image_reconstructed", str("data:;base64," + base64.b64encode(bmp_data_bytes).decode()))
        time.sleep(0.1)

@socketio.on("acquisition_end")
def acquisition_end(message):
    print(f"received message: {message}")
    global acquisition_ongoing
    acquisition_ongoing = False

@socketio.on("message")
def handleMessage(msg):
    print("Message: " + msg)
    #socketio.send(msg, broadcast=True) # broadcast=True：广播 服务器收到某个客户发来的data，并把该data转发给所有连接到该服务器的客户
    socketio.emit("message", msg)

@socketio.on("image_display_test")
def image_display_test(message):
    print(f"received message: {message}")

    img = Image.open("./matlab_scripts/const_file/HHb_result.bmp")

    image_object = io.BytesIO()
    img.save(image_object, "png")
    png_data_bytes = image_object.getvalue()
    socketio.emit("display_image", str(png_data_bytes))


# 运行Flask应用，开启调试模式
if __name__ == "__main__":
    #app.run(debug = True)
    socketio.run(config.app, debug=True)